package com.sky.controller.user;
import com.alibaba.fastjson.JSON;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "浏览菜品相关接口:二")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @GetMapping("/list")
    @ApiOperation(value = "根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        String key = "dish_" + categoryId;
        List<String> stringList = stringRedisTemplate.opsForList().range(key, 0, -1);
        if (stringList != null && !stringList.isEmpty()) {
            System.out.println("直接从缓存里查数据");
            List<DishVO> list = new ArrayList<>();
            for(String string:stringList){
                list.add(JSON.parseObject(string, DishVO.class));
            }
            return Result.success(list);
        }
        else {
            System.out.println("缓存里没有数据");
            List<DishVO> list = dishService.list(categoryId);
            for(DishVO dishVO:list){
                stringRedisTemplate.opsForList().rightPush(key, JSON.toJSONString(dishVO));
            }
            return Result.success(list);
        }
    }
}
